Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge’s serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
方法1:链表长度
从头指针遍历链表得到链表长度,然后找到中间。此处对于偶数长度的链表返回后面一个结点对象,因而可以直接返回cur.next。如果要返回前面一个结点对象,则需要对奇偶情况分别输出。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode cur = head;
int count = 0;
while (cur != null) {
count++;
cur = cur.next;
}
cur = head;
for (int i = 1; i <= count / 2; i++) {
cur = cur.next;
}
return cur.val;
}
}
方法二:双指针
fast和slow快慢双指针,fast每次走两步,slow每次走一步,偶数长度的链表fast.next==null说明已经走到尾部,奇数长度的链表fast.next.next == null说明已经走到尾部。
1 | class Solution { |